<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggleDialog" :class="{ active }">
      <span v-if="!fullLocation" class="placeholder"> 请选择收货地址 </span>
      <span v-else class="placeholder"> {{ fullLocation }} </span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="active">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span
          @click="changeCity(item)"
          class="ellipsis"
          v-for="item in cityObj"
          :key="item.code"
          >{{ item.name }}</span
        >
      </template>
    </div>
  </div>
</template>
<script>
import { ref, computed, reactive } from "vue";
import { onClickOutside } from "@vueuse/core";
import axios from "axios";
export default {
  name: "XtxCity",
  props: {
    fullLocation: String,
  },
  setup(props, { emit }) {
    // 这个是省市区的数据
    let currList = ref([]);
    //加载的动画效果
    const loading = ref(false);
    // 控制展开收起,默认收起
    const active = ref(false);
    // 打开弹框
    const openDialog = () => {
      active.value = true;
    };
    // 关闭弹框
    const closeDialog = () => {
      active.value = false;
    };
    // 切换展开收起
    const toggleDialog = () => {
      if (active.value) closeDialog();
      else {
        open();
      }
    };
    // 要给盒子绑定一个 ref
    const target = ref(null);
    // 点击其他位置隐藏
    onClickOutside(target, () => {
      closeDialog();
    });

    // 提供打开和关闭函数  再次打开让他 重新选三级联动
    const open = () => {
      // 显示的弹框打开
      active.value = true;
      //  loading 加载打开
      loading.value = true;
      // 获取三级联动的数据
      getCityData().then((res) => {
        console.log(res);
        currList.value = res;
      });
      // 请求之后 关掉loding 加载
      loading.value = false;
      // 清空之前选择
      for (const key in changeResult) {
        changeResult[key] = "";
      }
    };

    // 计算属性实现 地区的展示
    const cityObj = computed(() => {
      let list = currList.value;
      // 这个是找到市区的数据
      if (changeResult.provinceCode && changeResult.provinceName) {
        list = list.find((item) => item.code === changeResult.provinceCode)
          .areaList;
      }
      // 这个是找到县的数据
      if (changeResult.cityCode && changeResult.cityName) {
        list = list.find((item) => item.code === changeResult.cityCode)
          .areaList;
      }
      return list;
    });
    // 定义省市区的数据
    const changeResult = reactive({
      provinceCode: "",
      provinceName: "",
      cityCode: "",
      cityName: "",
      countyCode: "",
      countyName: "",
      fullLocation: "",
    });

    // 当你点击按钮的时候记录  当前你点击的数据 发给后端
    function changeCity(item) {
      console.log(item);
      // 省的数据
      if (item.level == 0) {
        changeResult.provinceCode = item.code;
        changeResult.provinceName = item.name;
      }
      // 市的数据
      if (item.level == 1) {
        changeResult.cityCode = item.code;
        changeResult.cityName = item.name;
      }
      // 县的数据
      if (item.level == 2) {
        changeResult.countyCode = item.code;
        changeResult.countyName = item.name;
        // 拼接一下地址的选择
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName} `;
        // 已经选完了 关闭弹框
        closeDialog();
        // 总地区
        emit("changeCity", changeResult);
        console.log(changeResult.fullLocation);
      }
      console.log(changeResult);
    }
    return {
      active,
      toggleDialog,
      target,
      currList,
      changeCity,
      cityObj,
      loading,
    };
  },
};

// 获取城市数据
// 1. 数据在哪里？https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
// 2. 何时获取？打开城市列表的时候，做个内存中缓存
// 3. 怎么使用数据？定义计算属性，根据点击的省份城市展示
const getCityData = () => {
  // 这个位置可能有异常操作，封装成promise
  return new Promise((resolve, reject) => {
    if (window.cityData) {
      // 有缓存
      resolve(window.cityData);
    } else {
      // 无缓存
      const url =
        "https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json";
      axios.get(url).then((res) => {
        window.cityData = res.data;
        resolve(window.cityData);
      });
    }
  });
};
</script>
<style scoped lang="scss">
// 加载样式
.option {
  // 省略...
  .loading {
    height: 290px;
    width: 100%;
    background: url(../../assets/images/load.gif) no-repeat center;
  }
}
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
